/**
 * allows for downloading of grid data (store) directly into excel
 * Method: extracts data of gridPanel store, uses columnModel to construct XML excel document,
 * converts to Base64, then loads everything into a data URL link.
 *
 * @author		Animal		<extjs support team>
 *
 */

/**
 * base64 encode / decode
 *
 * @location 	http://www.webtoolkit.info/
 *
 */

var Base64 = (function() {
    // Private property
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // Private method for UTF-8 encoding
    function utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    }

    // Public method for encoding
    return {
        encode : (typeof btoa == 'function') ? function(input) {
            return btoa(utf8Encode(input));
        } : function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = utf8Encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                keyStr.charAt(enc1) + keyStr.charAt(enc2) +
                keyStr.charAt(enc3) + keyStr.charAt(enc4);
            }
            return output;
        }
    };
})();

Ext.override(Ext.grid.GridPanel, {
    getExcelXml: function(includeHidden) {
        var worksheet = this.createWorksheet(includeHidden);
        var totalWidth = this.getColumnModel().getTotalWidth(includeHidden);
        return '<xml version="1.0" encoding="utf-8">' +
				'<?mso-application progid="Excel.Sheet"?>' +
				'<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">'+
				'<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">'+
				'<Title>' + this.title + '</Title>'+
				 '</DocumentProperties>'+
				 '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">'+
				  '<WindowHeight>' + worksheet.height + '</WindowHeight>'+
				  '<WindowWidth>' + worksheet.width + '</WindowWidth>'+
				  '<WindowTopX>120</WindowTopX>'+
				  '<WindowTopY>30</WindowTopY>'+
				  '<ProtectStructure>False</ProtectStructure>'+
				  '<ProtectWindows>False</ProtectWindows>'+
				  '</ExcelWorkbook>'+
				   '<Styles>'+
				   '<Style ss:ID="Default" ss:Name="Normal">'+
				    '<Alignment ss:Vertical="Center"/>'+
				    '<Borders/>'+
				    '<Font ss:FontName="宋体" x:CharSet="134" ss:Size="12"/>'+
				    '<Interior/>'+
				    '<NumberFormat/>'+
				    '<Protection/>'+
				   '</Style>'+
				   '<Style ss:ID="s21">'+
				    '<Alignment ss:Horizontal="Center" ss:Vertical="Center"/>'+
				   '</Style>'+
				   '<Style ss:ID="s23">'+
				    '<Alignment ss:Horizontal="Center" ss:Vertical="Center"/>'+
				    '<Borders>'+
				    ' <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				    ' <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				    ' <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				    ' <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				    '</Borders>'+
				   '</Style>'+
				   '<Style ss:ID="s24">'+
				   ' <Alignment ss:Horizontal="Center" ss:Vertical="Center"/>'+
				    '<Borders>'+
				    ' <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				    ' <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				     '<Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				     '<Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>'+
				   ' </Borders>'+
				   ' <Font ss:FontName="宋体" x:CharSet="134"/>'+
				   '</Style>'+
				   '<Style ss:ID="s30">'+
				   ' <Alignment ss:Horizontal="Center" ss:Vertical="Center"/>'+
				   ' <Font ss:FontName="宋体" x:CharSet="134" ss:Size="16"/>'+
				   '</Style>'+
				   '<Style ss:ID="s31">'+
				    '<Alignment ss:Horizontal="Left" ss:Vertical="Center"/>'+
				   ' <Font ss:FontName="宋体" x:CharSet="134"/>'+
				   '</Style></Styles>'+
				   


            worksheet.xml +
            '</Workbook>';
    },

    createWorksheet: function(includeHidden) {
        // Calculate cell data types and extra class names which affect formatting
        var cellType = [];
        var cellTypeClass = [];
        var cm = this.getColumnModel();
        var totalWidthInPixels = 0;
        var colXml = '';
        var headerXml = '';
        var visibleColumnCountReduction = 0;
        var colCount = cm.getColumnCount();
        for (var i = 0; i < colCount; i++) {
            if ((cm.getDataIndex(i) != '')
                && (includeHidden || !cm.isHidden(i))) {
                var w = cm.getColumnWidth(i)
                totalWidthInPixels += w;
                if (cm.getColumnHeader(i) === ""){
                	cellType.push("None");
                	cellTypeClass.push("");
                	++visibleColumnCountReduction;
                }
                else
                {
                    colXml += '<ss:Column ss:AutoFitWidth="1" ss:Width="' + w + '" />';
                    headerXml += '<ss:Cell ss:StyleID="headercell">' +
                        '<ss:Data ss:Type="String">' + cm.getColumnHeader(i) + '</ss:Data>' +
                        '<ss:NamedCell ss:Name="Print_Titles" /></ss:Cell>';
                    var fld = this.store.recordType.prototype.fields.get(cm.getDataIndex(i));
                    switch(fld.type) {
                        case "int":
                            cellType.push("Number");
                            cellTypeClass.push("int");
                            break;
                        case "float":
                            cellType.push("Number");
                            cellTypeClass.push("float");
                            break;
                        case "bool":
                        case "boolean":
                            cellType.push("String");
                            cellTypeClass.push("");
                            break;
                        case "date":
                            cellType.push("DateTime");
                            cellTypeClass.push("date");
                            break;
                        default:
                            cellType.push("String");
                            cellTypeClass.push("");
                            break;
                    }
                }
            }
        }
        var visibleColumnCount = cellType.length - visibleColumnCountReduction;

        var result = {
            height: 9000,
            width: Math.floor(totalWidthInPixels * 30) + 50
        };
       var ittest = this.store.data.items;
       var itrows = String(ittest.length+4);
        // Generate worksheet header details.
        var t ='<Worksheet ss:Name="Sheet1">'+
				  '<Names>'+
				  ' <NamedRange ss:Name="Print_Titles" ss:RefersTo="=Sheet1!R1:R4"/>'+
				  '</Names>'+
				  '<Table ss:ExpandedColumnCount="8" ss:ExpandedRowCount="' + itrows +'" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="14.25">'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="30"/>'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="27.75"/>'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="59.25"/>'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="29.25"/>'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="202.5"/>'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="56.25"/>'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="31.5"/>'+
				   '<Column ss:StyleID="s21" ss:AutoFitWidth="0" ss:Width="48"/>'+
				   '<Row ss:AutoFitHeight="0" ss:Height="45.75">'+
				    '<Cell ss:MergeAcross="7" ss:StyleID="s30"><Data ss:Type="String">归 档 文 件 目 录</Data><NamedCell  ss:Name="Print_Titles"/></Cell>'+
				   '</Row>'+
				   '<Row ss:AutoFitHeight="0" ss:Height="21">'+
				    '<Cell ss:MergeAcross="7" ss:StyleID="s31"><Data ss:Type="String">    全宗号：    保管期限：    室编盒号：      馆编盒号：</Data><NamedCell ss:Name="Print_Titles"/></Cell>'+
				   '</Row>'+
				   '<Row>'+
				    '<Cell ss:MergeAcross="1" ss:StyleID="s24"><Data ss:Type="String">件  号</Data><NamedCell  ss:Name="Print_Titles"/></Cell>'+
				    '<Cell ss:MergeDown="1" ss:StyleID="s24"><Data ss:Type="String">责任者</Data><NamedCell  ss:Name="Print_Titles"/></Cell>'+
				    '<Cell ss:MergeDown="1" ss:StyleID="s24"><Data ss:Type="String">文号</Data><NamedCell  ss:Name="Print_Titles"/></Cell>'+
				    '<Cell ss:MergeDown="1" ss:StyleID="s24"><Data ss:Type="String">题           名</Data><NamedCell ss:Name="Print_Titles"/></Cell>'+
				    '<Cell ss:MergeDown="1" ss:StyleID="s24"><Data ss:Type="String">日期</Data><NamedCell ss:Name="Print_Titles"/></Cell>'+
				    '<Cell ss:MergeDown="1" ss:StyleID="s24"><Data ss:Type="String">页数</Data><NamedCell ss:Name="Print_Titles"/></Cell>'+
				    '<Cell ss:MergeDown="1" ss:StyleID="s24"><Data ss:Type="String">备注</Data><NamedCell ss:Name="Print_Titles"/></Cell>'+
				  ' </Row>'+
				   '<Row>'+
				   ' <Cell ss:StyleID="s24"><Data ss:Type="String">馆编</Data><NamedCell ss:Name="Print_Titles"/></Cell>'+
				    '<Cell ss:StyleID="s24"><Data ss:Type="String">室编</Data><NamedCell ss:Name="Print_Titles"/></Cell>'+
				   '</Row>';
        
        
        
        
//        '<ss:Worksheet ss:Name="' + this.title + '">' +
//            '<ss:Names>' +
//            '<ss:NamedRange ss:Name="Print_Titles" ss:RefersTo="=\'' + this.title + '\'!R1:R2" />' +
//            '</ss:Names>' +
//            '<ss:Table x:FullRows="1" x:FullColumns="1"' +
//            ' ss:ExpandedColumnCount="' + (visibleColumnCount + 2) +
//            '" ss:ExpandedRowCount="' + (this.store.getCount() + 2) + '">' +
//            colXml +
//            '<ss:Row ss:Height="38">' +
//            '<ss:Cell ss:StyleID="title" ss:MergeAcross="' + (visibleColumnCount - 1) + '">' +
//            '<ss:Data xmlns:html="http://www.w3.org/TR/REC-html40" ss:Type="String">' +
//            '<html:B>Generated by ExtJS</html:B></ss:Data><ss:NamedCell ss:Name="Print_Titles" />' +
//            '</ss:Cell>' +
//            '</ss:Row>' +
//            '<ss:Row ss:AutoFitHeight="1">' +
//            headerXml +
//            '</ss:Row>';

        // Generate the data rows from the data in the Store
        for (var i = 0, it = this.store.data.items, l = it.length; i < l; i++) {
            t += '<Row>';
          //  var cellClass = (i & 1) ? 'odd' : 'even';
            r = it[i].data;
            var k = 0; 
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String"></Data></Cell>';
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String"></Data></Cell>';
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String">粮油集团</Data></Cell>';
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String">'+r[cm.getDataIndex(0)]+'</Data></Cell>';
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String">'+r[cm.getDataIndex(3)]+'</Data></Cell>';           
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String">'+r[cm.getDataIndex(1)]+'</Data></Cell>';
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String"></Data></Cell>';
            t += '<Cell ss:StyleID="s24"><Data ss:Type="String"></Data></Cell>';
//            for (var j = 0; j < colCount; j++) {
//                if ((cm.getDataIndex(j) != '')
//                    && (includeHidden || !cm.isHidden(j))) {
//                    var v = r[cm.getDataIndex(j)];
//                    if (cellType[k] !== "None") {
//                        t += '<Cell ss:StyleID="s23"><Data ss:Type="' + cellType[k] + '">';
//                        if (cellType[k] == 'DateTime') {
//                            t += v.format('Y-m-d'); 
//                        } else {
//                            t += v;
//                        }
//                        t +='</Data></Cell>';
//                    }
//                    k++;
//                }
//            }
            t += '</Row>';
        }

        result.xml = t + '</Table>' +
            			'<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">' +
					   '<PageSetup>' +
					    '<Header x:Margin="0.51181102362204722"/>' +
					    '<Footer x:Margin="0.51181102362204722"/>' +
					    '<PageMargins x:Bottom="0.98425196850393704" x:Left="0.74803149606299213" x:Right="0.74803149606299213" x:Top="0.98425196850393704"/>' +
					   '</PageSetup>' +
					  ' <Print>' +
					   ' <ValidPrinterInfo/>' +
					   ' <PaperSizeIndex>9</PaperSizeIndex>' +
					   ' <HorizontalResolution>300</HorizontalResolution>' +
					   ' <VerticalResolution>300</VerticalResolution>' +
					   '</Print>' +
					   '<Selected/>' +
					   '<FreezePanes/>' +
					   '<FrozenNoSplit/>' +
					   '<SplitHorizontal>4</SplitHorizontal>' +
					   '<TopRowBottomPane>4</TopRowBottomPane>' +
					   '<ActivePane>2</ActivePane>' +
					   '<Panes>' +
					    '<Pane>' +
					     '<Number>3</Number>' +
					    '</Pane>' +
					    '<Pane>' +
					     '<Number>2</Number>' +
					     '<ActiveRow>0</ActiveRow>' +
					     '<ActiveCol>15</ActiveCol>' +
					    '</Pane>' +
					   '</Panes>' +
					   '<ProtectObjects>False</ProtectObjects>' +
					  ' <ProtectScenarios>False</ProtectScenarios>' +
					  '</WorksheetOptions>' +
					' </Worksheet>';
        return result;
    }
});
